package state.component;
import java.io.IOException;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

public class FileOutputStream {
	private FileConnection fileConnection;
	private OutputStream outputStream;
	private final int BUFFER_LEN = 10 * 1024 * 10 + 5;
	private byte[] buffer = new byte[BUFFER_LEN];
	private int bufferPointer = 0;

	public FileOutputStream(String file, boolean append) throws IOException {
		createFile(file);
		fileConnection = (FileConnection) Connector.open(file, Connector.READ_WRITE);
		fileConnection.setWritable(true);
		outputStream = fileConnection.openOutputStream();
	}

	private void createFile(String file) {
		FileConnection filecon = null;
		try {
			filecon = (FileConnection) Connector.open(file);
			if (!filecon.exists()) {
				filecon.create();
			}
		} catch (IOException ioe) {
		} finally {
			try {
				if (filecon != null) {
					filecon.close();
				}
			} catch (IOException e) {
			}
		}
	}

	public void close() throws IOException {
		flush();
		try {
			if (outputStream != null) {
				outputStream.close();
			}
		} finally {
			if (fileConnection != null) {
				fileConnection.close();
			}
		}
	}

	public void write(byte[] byteArray, int len) throws IOException {
		if (len >= (buffer.length - bufferPointer)) {
			flush();
		}
		System.arraycopy(byteArray, 0, buffer, bufferPointer, len);
		bufferPointer += len;
	}

	public void flush() throws IOException {
		if (bufferPointer > 0) {
			byte[] des = new byte[bufferPointer];
			System.arraycopy(buffer, 0, des, 0, bufferPointer);
			outputStream.write(des);
			outputStream.flush();
			buffer = new byte[BUFFER_LEN];
			bufferPointer = 0;
		}
	}
}
